package com.theaf.basemodule.web.controller;

import com.theaf.core.utils.DateUtils;
import com.theaf.core.web.ResultHandler;
import io.swagger.annotations.ApiImplicitParam;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * @Author:songwenke
 * @Description:文件上传
 * @Date:create in 9:53 2018/5/28
 * @Modified By:
 **/
@RestController
public class FileController {
    @Value("${smyw.file.upload.catalog}")
    private String catalog;

    @PostMapping("/upload")
    @ResponseBody
    public Object upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        String fileCatalog = System.getProperty("user.dir")+catalog+"/";
        File fc = new File(fileCatalog);
        if(!fc.exists()){
            fc.mkdirs();
        }
        String item = DateUtils.convertDateToStr(new Date(System.currentTimeMillis()),"yyyyMM");
        fc = new File(fileCatalog);
        if(!fc.exists()){
            fc.mkdirs();
        }
        item+="/"+UUID.randomUUID().toString().replaceAll("-","")
                +"."+file.getOriginalFilename().split("\\.")[1];
        String filePath = fileCatalog+item;
        File dest = new File(filePath);
        try {
            dest.createNewFile();
            file.transferTo(dest);
            Map rets = new HashMap();
            rets.put("title",file.getOriginalFilename());
            rets.put("path",item);
            return ResultHandler.success(rets);
        } catch (IOException e) {
            return ResultHandler.errorWrapper(e);
        }
    }

    @PostMapping("/multiUpload")
    @ResponseBody
    public Object multiUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        List infos = new ArrayList();
        List<File> fs = new ArrayList();
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            if (file.isEmpty()) {
                continue;
            }
            String fileCatalog = System.getProperty("user.dir")+catalog+"/";
            File fc = new File(fileCatalog);
            if(!fc.exists()){
                fc.mkdirs();
            }
            String item = DateUtils.convertDateToStr(new Date(System.currentTimeMillis()),"yyyyMM");
            fc = new File(fileCatalog);
            if(!fc.exists()){
                fc.mkdirs();
            }
            item+="/"+UUID.randomUUID().toString().replaceAll("-","")
                    +"."+file.getOriginalFilename().split("\\.")[1];
            String filePath = fileCatalog+item;
            File dest = new File(filePath);
            try {
                file.transferTo(dest);
                Map rets = new HashMap();
                rets.put("title",file.getOriginalFilename());
                rets.put("path",item);
                infos.add(rets);
                fs.add(dest);
            } catch (IOException e) {
                for(File f:fs){
                    f.deleteOnExit();
                }
                return ResultHandler.errorWrapper(e);
            }
        }
        return ResultHandler.success(infos);
    }

    @GetMapping("/download")
    @ApiImplicitParam(value = "标识" , name = "id" , dataType = "String" , paramType = "query")
    public void download(String id,HttpServletRequest request,HttpServletResponse response) throws Exception{
        try{
            InputStream inputStream = new FileInputStream(new File(System.getProperty("user.dir")+catalog+"/"+id));
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename="+id.substring(id.lastIndexOf("/")));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
